package DatabaseCommands;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class Table{

	protected String TableName=null;
	protected List<String> Columns;
	protected ArrayList<ArrayList<String>> Keys;
	protected Connection DatabaseConnection=null;
	
	public Table(String Name,Connection C) throws SQLException{
		TableName=Name;
		DatabaseConnection=C;
		GetColumns();
	}
	
	
	public String GetTableName(){
		return TableName;
	}
	
	
	public List<String> GetColumns(){
		Columns=new ArrayList<String>();
		
		try{
			ResultSet Results=DatabaseConnection.getMetaData().getColumns(null,null,TableName,null);
			while(Results.next()){
				Columns.add(Results.getString(4));
			}
		}catch(Exception E){}
		
		return Columns;
	}
	
	
	public ArrayList<ArrayList<String>> GetKeys(){
		Keys=new ArrayList<ArrayList<String>>();
		List<String> Temp=new ArrayList<String>();
		
		try{
			ResultSet Results=DatabaseConnection.getMetaData().getImportedKeys(null,null,TableName);
			while(Results.next()){
				Temp.add(Results.getString("FKCOLUMN_NAME"));//Local Table Column
				Temp.add(Results.getString("PKTABLE_NAME"));//Table to reference
				Temp.add(Results.getString("PKCOLUMN_NAME"));//Column on reference table
				Keys.add(new ArrayList<String>(Temp));
				Temp.clear();
			}
		}catch(Exception E){}
		
		return Keys;
	
	}
	
	
	protected void PrintTable() throws SQLException{
		for(String Column:Columns){
			System.out.printf("%s",Column);
		}
		System.out.println();
		
		ResultSet Results=DatabaseConnection.createStatement().executeQuery("Select * From Book");
		while(Results.next()){
			for(int x=1;x<=Columns.size();x++){
				System.out.printf("%s",Results.getString(x));
			}
			System.out.println();
		}
		
		
	}
	
}

